<template>
  <div>
    <div class="info row">
      <div class="imgB center">
        <img
          width="300"
          :src="`${url}` +`${bookInfo.coverPhoto}`"
          alt=""
        />
      </div>
      <div class="main col">
        <div class="bookName">{{ bookInfo.bookName }}</div>
        <div class="bookInfo rows">
          <template v-for="item in bookAttr">
            <div class="bookAttr">
              <i class="attr">{{ item.name }}:</i>
              <i class="value">{{ bookInfo[item.attr] }}</i>
            </div>
          </template>
        </div>
        <div class="row">
          <div class="buy">
            <template v-for="item in priceAttr">
              <div class="priceAttr">
                <i class="attr">{{ item.name }}:</i>
                <i
                  class="value"
                  v-if="item.attr != 'discount' || bookInfo.discount != 10"
                >
                  <i v-if="item.attr == 'nprice' || item.attr == 'fprice'"
                    >￥</i
                  >
                  <i>{{ bookInfo[item.attr] }} </i>
                  <i v-if="item.attr == 'discount'">折</i>
                  <i v-else-if="item.attr == 'depreciation'">成新</i></i
                >
                <i class="value" v-else> 无折扣 </i>
              </div>
            </template>
          </div>
          <div class="more row">
            <div class="hand row">
              <img
                class="handImg"
                ref="hand"
                width="50"
                height="50"
                src="@/assets/imgs/hand.png"
                alt=""
              />
              <div class="message">
                <div class="text1">关注公众号</div>
                <div class="text2 row">
                  立减
                  <div ref="five" class="five">5</div>
                  元
                </div>
              </div>
            </div>
            <img
              width="100"
              height="100"
              src="@/assets/imgs/wx.png"
              alt=""
            />
          </div>
        </div>
        <div class="priceAttr row">
          <i class="attr">商家地址: {{ issuerInfo.address }}</i>
        </div>
        <div class="priceAttr row">
          <i class="attr">购买数量:</i>
          <i class="value nums">
            <button
              @click="reduceCartNum()"
              class="desc"
              :disabled=" BCLInfo.cartNum  == 1"
            >
              -</button
            ><i class="num">{{ BCLInfo.cartNum }} </i
            ><button
              @click="addCartNum()"
              class="add"
              :disabled=" BCLInfo.cartNum  == bookInfo.quantity"
            >
              +
            </button>
          </i>
          <i class="quantitys">库存：{{ bookInfo.quantity }}</i>
        </div>
        <div class="Bottomprice">
          <i class="countPrice"
            >￥
            {{
              bookInfo.price
            }}</i
          >
          <el-button class="toCart" size="medium" @click="toBuy()"
            >购买</el-button
          >
          <i class="toLike el-icon-shopping-cart-2 hovers" @click="saveCart()">
            加入购物车</i
          >
          <i class="toLike el-icon-star-off hovers" @click="toLike()">
            {{ BCLInfo.clStatus==1||BCLInfo.clStatus==3 ? "已收藏" : "收藏" }}</i
          >
        </div>
      </div>
      <rightAside></rightAside>
    </div>
    <el-dialog
      class="toPay center"
      width="220px"
      title="请用微信扫码支付"
      :visible.sync="toPayVisible"
      @close="closePay()"
    >
    <div class="center">
<el-image
        
        v-if="payAddr"
        style="width: 100px; height: 100px"
        :src="`${url}`+`${payAddr}`"
      >
      <div slot="error" class="image-slot">
        <i>支付失败，请检查网络</i></i>
      </div>
      </el-image>
    </div>
      
    </el-dialog>
  </div>
</template>

<script>
import { onlyNumOnePoint, dateFormat } from "@/assets/myjs/function.js";
export default {
  data() {
    return {
      url: localStorage.getItem("url"),
      bookInfo: {},
      order: {},
      payAddr: "",
      bookAttr: [
        { name: "作者", attr: "author", code: "" },
        { name: "出版社", attr: "publisher", code: "" },
        { name: "关键字", attr: "keyword", code: "" },
        { name: "出版日期", attr: "pubDate", code: "" },
        { name: "ISBN", attr: "isbn", code: "" },
        { name: "原价", attr: "fprice", code: "" },
        { name: "存货", attr: "quantity", code: "" },
        { name: "销量", attr: "sellNum", code: "" },
        { name: "收藏", attr: "likeNum", code: "" },
      ],
      priceAttr: [
        { name: "原价", attr: "fprice", code: "" },
        { name: "标价", attr: "nprice", code: "" },
        // { name: "收藏店家有折扣", attr: "discount", code: "" },
        // { name: "成交单价", attr: "price", code: "" },
        { name: "折损", attr: "depreciation", code: "" },
      ],
      issuerInfo: {},
      BCLInfo: {
        bookId: 0,
        userId: 0,
        cartNum: 1,
        clStatus: 0,
      },
      cartFlog: false,
      likeFlog: false,
      toPayVisible: false,
      setTiFlog: null,
      canclePay: false,
    };
  },
  computed: {
    userId: function () {
      return this.$store.state.user.user.userId;
    },
  },
  mounted() {
    console.log("query.bookId:", this.$route.query.bookId);
    this.BCLInfo.bookId = Number(this.$route.query.bookId);
    this.getBookInfo();
  },
  components: {
    rightAside: () => import("@/components/base/rightAside.vue"),
  },
  methods: {
    onlyNumOnePoint,
    getBCLInfo() {
      console.log("getBCLInfo");
      //是否已经有记录
      this.$axios
        .get(
          `sys/bookCartLike/getBCLByUserId?userId=${this.userId}&bookId=${this.bookInfo.bookId}`
        )
        .then(({ data }) => {
          console.log("BCLInfo:", data.BCLInfo);
          // clStatus:收藏1或购物车2都有3
          if (data.BCLInfo) {
            this.BCLInfo = JSON.parse(JSON.stringify(data.BCLInfo));
            if (data.BCLInfo.clStatus != 1) {
              this.cartFlog = true;
            }
            if (data.BCLInfo.clStatus != 2) {
              this.likeFlog = true;
            }
            // if (data.BCLInfo.clStatus == 3 || data.BCLInfo.clStatus == 2) {
            //   this.$set(this.BCLInfo, "cartNum", data.BCLInfo.cartNum);
            // } else {
            //   this.$set(this.BCLInfo, "cartNum", 1);
            // }
          } else {
            this.$set(this.BCLInfo, "clStatus", 0);
          }
        });
      this.$set(this.BCLInfo, "cartNum", 1);
    },
    getBookInfo() {
      this.$axios
        .get(
          "index/sys/book/getBookByBookId?bookId=" + this.$route.query.bookId
        )
        .then((res) => {
          if (res.status == 200) {
            console.log("yes:", res.data);
            this.bookInfo = res.data.bookInfo;
            this.$set(this.bookInfo, "cartNum", 1);
            this.$set(this.BCLInfo, "cartNum", 1);
            // this.bookInfo.price = onlyNumOnePoint(
            //   (this.bookInfo.nprice * this.bookInfo.discount) / 10
            // );
            //商家地址联系信息
            this.$axios
              .get("sys/user/getUserByUserId/" + this.bookInfo.userId)
              .then(({ data }) => {
                this.issuerInfo = data.userInfo;
                console.log("issuerInfo:", this.issuerInfo);
              });

            //是否已经有收藏、购物车记录
            if (this.userId) {
              this.getBCLInfo();
            }
            console.log(`img:${this.url}` + `${this.bookInfo.coverPhoto}`);
          }
        });
    },
    reduceCartNum() {
      // console.log("reduce");
      this.BCLInfo.cartNum--;
    },
    addCartNum() {
      // console.log("add");

      this.BCLInfo.cartNum++;
    },
    addOrder() {
      // this.order=JSON.parse(JSON.stringify(this.bookInfo));
      this.$set(this.order, "userId", this.$store.state.user.user.userId);
      this.$set(this.order, "bookId", this.bookInfo.bookId);
      this.$set(this.order, "quantity", this.BCLInfo.cartNum);
      this.$set(this.order, "price", this.bookInfo.price);
      this.$set(
        this.order,
        "money",
        this.bookInfo.price * this.BCLInfo.cartNum
      );
      this.$set(this.order, "orderStatus", 1);
      this.$set(
        this.order,
        "orderCreateTime",
        dateFormat("YYYY-mm-dd HH:MM:SS", new Date())
      );
      console.log("addOrder:", this.order);
      this.$axios.post("sys/bookOrder/add", this.order).then(({ data }) => {
        console.log(data);
        this.order.orderId = data.bookOrder.orderId;
      });
      this.getBookInfo();
    },
    buySuccess() {
      // this.order.orderStatus = 2;
      // this.$set(this.order, "orderStatus", 2);
      // this.$axios.post("sys/bookOrder/updata", this.order).then(({ data }) => {
      //   console.log(data);
      // });
    },
    toBuy() {
      this.checkToken();
      // orderStatus
      // 订单状态：1待付款  2待商家确认 3待收货 4待确认收货 5待评论 6退货退款中 7已签收 8已退货退款 9已取消 10商家取消
      this.$axios.post("sys/book/pay").then(({ data }) => {
        console.log("toBuy", data);
        if (data.payAddr) {
          this.payAddr = data.payAddr;
          this.toPayVisible = true;
          this.addOrder();
          this.setTiFlog = setTimeout(() => {
            this.toPayVisible = false;
            this.buySuccess();
            this.$message.success("支付成功");
            console.log("setTimeout");
          }, 3000);
        }
      });
    },
    closePay() {
      if (this.setTiFlog) {
        clearTimeout(this.setTiFlog);
      }
      console.log("closePay");
      // this.addOrder();
      // this.$message.warning("取消支付!(30分组内可在待支付订单查看)");
    },
    // updateInfo(status) {
    //   this.BCLInfo.bookId = this.bookInfo.bookId;
    //   this.$set(this.BCLInfo, "userId", this.bookInfo.userId);
    //   this.$set(this.BCLInfo, "cartNum", this.bookInfo.cartNum);
    //   this.$set(this.BCLInfo, "clStatus", status);
    // },
    saveCart() {
      this.checkToken();
      let cart = {
        userId: this.$store.state.user.user.userId,
        bookId: this.BCLInfo.bookId,
        cartNum: this.BCLInfo.cartNum,
      };
      this.$axios.post("sys/bookCartLike/saveCart", cart).then(({ data }) => {
        if (data.code == 201) {
          this.$message.success("成功！");
        } else {
          this.$message.error("加入购物车失败");
        }
      });
    },
    toLike() {
      this.checkToken();
      if (!this.$store.state.user.user.userId) {
        this.$router.push({
          path: "/login",
          query: { url: "/details", bookId: this.$route.query.bookId },
        });
        return;
      }
      let like = {
        userId: this.$store.state.user.user.userId,
        bookId: this.bookInfo.bookId,
      };

      if (this.BCLInfo.clStatus == 1 || this.BCLInfo.clStatus == 3) {
        this.$axios
          .post("sys/bookCartLike/deleteLike", like)
          .then(({ data }) => {
            if (data.code == 201) {
              this.$message.success("成功！");
            } else {
              this.$message.error("取消收藏失败");
            }
            this.getBCLInfo();
          });
      } else {
        this.$axios.post("sys/bookCartLike/saveLike", like).then(({ data }) => {
          if (data.code == 201) {
            this.$message.success("成功！");
          } else {
            this.$message.error("收藏失败");
          }
          this.getBCLInfo();
        });
      }
    },
    checkToken() {
      // console.log(
      //   "checkToken - this.$store.state.user.user.token = ",
      //   this.$store.state.user.user.token
      // );
      if (!this.$store.state.user.user.token) {
        this.$router.push({
          path: "/login",
          query: { url: "/details", bookId: this.$route.query.bookId },
        });
        return;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.info {
  padding: 30px;
  .imgB {
    width: 360px;
    height: 360px;
    border: 1px solid lightgrey;
    img {
      background: #000;
    }
  }
  .main {
    width: 600px;
    // background: #000;
    margin-left: 20px;
    margin-right: 20px;
    .bookName {
      font-size: 30px;
      font-weight: 600;
      margin-bottom: 26px;
    }
    .bookInfo {
      border-bottom: 1px solid lightgray;
      margin-bottom: 20px;
      .bookAttr {
        width: 33%;
        margin-bottom: 12px;
        font-size: 14px;
        color: lightslategrey;
        .attr {
          margin-right: 10px;
        }
        // .value {
        // }
      }
    }
    .priceAttr {
      // background: #000;
      margin-bottom: 20px;
      .attr {
        font-size: 14px;
        color: lightslategrey;
        margin-right: 10px;
        // .desc {
        // }
        // .add {
        // }
      }
      .value {
        font-size: 18px;
        color: red;
      }
      // .nums {
      //   // border: 1px solid lightgrey;
      // }
      .num {
        padding-left: 10px;
        padding-right: 10px;
      }
    }
  }

  .quantitys {
    color: lightslategrey;
    margin-left: 20px;
  }
}
.buy {
  min-width: 180px;
}
.more {
  margin: 20px 40px 20px 60px;
  background: lightgrey;
  padding: 8px;
  height: 120px;
  .hand {
    padding-top: 20px;
    position: relative;
    border: 4px solid lightcoral;
    width: 210px;

    img {
      position: absolute;
      left: 10px;
      top: 20px;
      margin-right: 50px;
    }
    .message {
      font-weight: 600;
      position: absolute;
      top: 20px;
      right: 20px;
      // margin-right: 30px;
      .text1 {
        margin-bottom: 20px;
      }
      .text2 {
        .five {
          margin-left: 10px;
          margin-right: 10px;
          color: red;
          animation: myscale 1s ease-in-out infinite;
          -webkit-animation: myscale 1s ease-in-out infinite;
        }
      }
    }
  }
}

.Bottomprice {
  margin-top: 40px;
  .m3 {
    margin-left: 30px;
  }
  .countPrice {
    font-size: 20px;
    color: red;
    .m3;
  }
  .toCart {
    color: rgb(250, 249, 247);
    background: red;
    padding: 16px 40px;
    font-weight: 600;
    font-size: 14px;
    .m3;
  }
  .toLike {
    .m3;
    color: lightslategrey;
  }
}
.hovers:hover {
  color: red;
  font-size: 16px;
  cursor: pointer;
}
</style>
<style>
@keyframes myscale {
  0% {
    transform: scale(1);
    /* background: #000; */
  }
  100% {
    transform: scale(2);
    /* background: rgb(234, 225, 225); */
  }
}
@keyframes myRemoveX {
  from {
    transform: translateX(0);
    /* background: #000; */
  }
  to {
    transform: translateX(10px);
    /* background: rgb(240, 234, 234); */
  }
}

.handImg {
  animation: myRemoveX 1s ease-in-out infinite;
}

.five {
  animation: myscale 1s ease-in-out infinite;
  -webkit-animation: myscale 1s ease-in-out infinite;
}
</style>